package e.odbo.data.android.sample.ui.state;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.openbravo.data.basic.BasicException;

import java.util.List;

import e.odbo.data.android.sample.App;
import e.odbo.data.android.sample.R;
import e.odbo.data.android.sample.dao.UserDAO;
import e.odbo.data.android.sample.entry.User;
import e.odbo.data.android.sample.ui.user.UserListViewModel;
import e.odbo.data.dao.EntityManager;
import e.odbo.data.dsl.query.QBF;

public class StateFragment extends Fragment {


    private UserListViewModel mViewModel;

    public static StateFragment newInstance() {
        return new StateFragment();
    }

    EntityManager entryManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        entryManager=((App) this.getActivity().getApplication()).getEntityManager();
    }


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view= inflater.inflate(R.layout.state_fragment, container, false);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        textView=view.findViewById(R.id.state_Text);
        //int count=-1;
        //UserDAO userDAO= (UserDAO) entryManager.getDao(User.class);
        //try {
        //    count=userDAO.count(QBF.all());
        //} catch (BasicException e) {
        //    e.printStackTrace();
        //}
        //textView.setText("总计：\n \t"+count+"条记录");
    }

    TextView textView;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = ViewModelProviders.of(getActivity()).get(UserListViewModel.class);
        // TODO: Use the ViewModel

        mViewModel.getUserList().observe(this, new Observer<List<User>>() {
                    @Override
                    public void onChanged(List<User> users) {
                        textView.setText("总计：\n \t"+users.size()+"条记录");
                    }
                }
        );
    }

}
